﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion.DesignerTool
{
    public class TrackedGameData
    {
        private ResourceItem parentResource;
        private NodeScript parentNodeScript;
        private NodeBase parentNode;
        private GameData gameData;

        public Dictionary<string, object> originalValueCollection;
        public string originalGameItemName;

        public TrackedGameData(ResourceItem parentResource, NodeScript parentNodeScript, NodeBase parentNode, GameData gameData)
        {
            this.parentResource = parentResource;
            this.parentNodeScript = parentNodeScript;
            this.parentNode = parentNode;
            this.gameData = gameData;
            this.originalGameItemName = gameData.GameItemName;

             originalValueCollection = new Dictionary<string, object>(gameData.PropertyDictionary);
        }

        public void TransferData()
        {
            if (originalGameItemName != gameData.GameItemName)
                GameDataTransfer.UpdateGameItemName(gameData.GameItemName, parentResource.Name, parentNodeScript.Name, parentNode, parentNode.GameDataCollection.IndexOf(gameData));

            CollectionDelta<string> collectionDelta = new CollectionDelta<string>(originalValueCollection.Keys, gameData.PropertyDictionary.Keys);

            List<string> copyOfOriginal = new List<string>(originalValueCollection.Keys);
            foreach (string deletedItem in collectionDelta.DeletedItems)
            {
                GameDataTransfer.RemoveProperty(parentResource.Name, parentNodeScript.Name, parentNode, gameData, deletedItem);
                copyOfOriginal.Remove(deletedItem);
            }

            List<string> copyOfCurrent = new List<string>(gameData.PropertyDictionary.Keys);
            foreach (string newItem in collectionDelta.NewItems)
                GameDataTransfer.AddProperty(parentResource.Name, parentNodeScript.Name, parentNode, copyOfCurrent.IndexOf(newItem), newItem, gameData.PropertyDictionary[newItem]);

            foreach (string identicalItems in collectionDelta.IdenticalItems)
            {
                if (GameEngine.GetStringRepresention(originalValueCollection[identicalItems]) != GameEngine.GetStringRepresention(gameData.PropertyDictionary[identicalItems]))
                    GameDataTransfer.Update(parentResource.Name, parentNodeScript.Name, parentNode, parentNode.GameDataCollection.IndexOf(gameData), identicalItems, gameData.PropertyDictionary[identicalItems]);
            }
        }
    }
}
